import { useState, useEffect, useRef, useCallback } from 'react';
import { Spin } from 'antd';
import BookCard from "../../components/BookCard/BookCard.tsx";
import Header from "../../components/Header/Header.tsx";
import Footer from "../../components/Footer/Footer.tsx";
import { listBookByPage } from '../../api/bookController';

const RecommendBooks = () => {
    const [books, setBooks] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);
    const [loadingMore, setLoadingMore] = useState(false);
    const [hasMore, setHasMore] = useState(true);
    const [currentPage, setCurrentPage] = useState(1);
    const observer = useRef<IntersectionObserver | null>(null);
    const loadingRef = useRef<HTMLDivElement>(null);

    const fetchBooks = async (isInitial = false) => {
        if (isInitial) {
            setLoading(true);
            setCurrentPage(1);
        } else {
            setLoadingMore(true);
        }

        try {
            const response = await listBookByPage({
                current: isInitial ? 1 : currentPage,
                pageSize: 8,
                bookname: "",
                bookauthor: "",
                categorycode: ["all"]
            });

            const newBooks = response.data.records;
            
            if (isInitial) {
                setBooks(newBooks);
            } else {
                setBooks(prev => [...prev, ...newBooks]);
            }

            // 检查是否还有更多数据
            setHasMore(response.data.current < response.data.pages);
            
            if (!isInitial) {
                setCurrentPage(prev => prev + 1);
            }
        } catch (error) {
            console.error('获取图书列表失败:', error);
        } finally {
            if (isInitial) {
                setLoading(false);
            } else {
                setLoadingMore(false);
            }
        }
    };

    const lastBookElementRef = useCallback((node: HTMLDivElement) => {
        if (loading || loadingMore) return;
        if (observer.current) observer.current.disconnect();
        
        observer.current = new IntersectionObserver(entries => {
            if (entries[0].isIntersecting && hasMore) {
                fetchBooks();
            }
        });

        if (node) observer.current.observe(node);
    }, [loading, loadingMore, hasMore]);

    useEffect(() => {
        fetchBooks(true);
        return () => {
            if (observer.current) {
                observer.current.disconnect();
            }
        };
    }, []);

    const handleViewDetail = (bookId: number) => {
        console.log('查看图书详情:', bookId);
        // 添加导航到详情页的逻辑
    };

    return (
        <div className="min-h-screen flex flex-col">
            <Header />
            <div className="flex-grow container mx-auto px-4 py-8">
                <h1 className="text-2xl font-bold mb-6">推荐图书</h1>
                
                {loading ? (
                    <div className="flex justify-center my-8">
                        <Spin size="large" />
                    </div>
                ) : (
                    <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
                        {books.map((book, index) => (
                            <div
                                key={book.id}
                                ref={index === books.length - 1 ? lastBookElementRef : null}
                            >
                                <BookCard
                                    book={{
                                        id: book.id,
                                        image: book.imageurl,
                                        name: book.bookname,
                                        title: `${book.bookauthor}著 - ${book.bookdesc}`,
                                        publishTime: book.publishdate?.split(' ')[0]
                                    }}
                                    onViewDetail={handleViewDetail}
                                />
                            </div>
                        ))}
                    </div>
                )}

                {loadingMore && (
                    <div className="flex justify-center my-8" ref={loadingRef}>
                        <Spin size="large" />
                    </div>
                )}

                {!hasMore && !loading && books.length > 0 && (
                    <div className="text-center text-gray-500 my-8">
                        没有更多数据了
                    </div>
                )}
            </div>
            <Footer />
        </div>
    );
};

export default RecommendBooks; 